package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.UrlUtility;

//import validation.UserLoginValidation;
import bizlogic.UserManager;
import model.UserDTO;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public LoginServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doShow(request, response);
	}
	
	private void doShow(HttpServletRequest req, HttpServletResponse res) {
		String address = "/WEB-INF/Login.jsp";
		
		if ( req.getSession(true).getAttribute("user") == null ) {
			// Set the attribute to pass the session checking
			req.setAttribute("isLoginPage", "yes");
			
			UrlUtility.forwardPage(req, res, address);
		} else {
			address = "Main";
			UrlUtility.redirectPage(res, address);
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		// TODO Auto-generated method stub
		doLogin(request, response);
	}
	
	private void doLogin(HttpServletRequest req, HttpServletResponse res) {
		UserManager um = new UserManager();
		UserDTO user = null;
		String address = "/WEB-INF/Login.jsp";
		
		// Put validation here
		
		user = um.doLogin(req.getParameter("userid"), req.getParameter("password"));
		System.out.println(user);
		
		if ( user == null ) { // Not valid user
			req.setAttribute("isLoginPage", "yes");
			req.setAttribute("error", "login.error.invaliduserpassword");
			
			UrlUtility.forwardPage(req, res, address);
		} else { // Valid user
			HttpSession hs = req.getSession(true);
			hs.setAttribute("user", user);
			
			UrlUtility.redirectPage(res, "Main");
		}
		
	}

}
